<template>
    <div style="position: relative;height:100%">
        <!-- 折线图 -->
        <div ref="chartDom" class="com-chart"></div>
        <div class="select-content">
            <div class="chart-btn-refresh" @click="refresh('条目同步走势')"></div>
            <el-date-picker
                v-model="lineParams.beginDate"
                type="date"
                placeholder="选择日期"
                size="mini"
                value-format="yyyyMMdd"
                format="yyyy/MM/dd"
                :picker-options="beginPickerOptions"
                :clearable="false"
                :editable="false"
                style="width:132px"
                @change="handleDateChange"
            >
                <!-- @change="dateChange('begin')" -->
            </el-date-picker>
            <span style="margin:auto 6px; color: #fff">至</span>
            <el-date-picker
                v-model="lineParams.endDate"
                type="date"
                placeholder="选择日期"
                size="mini"
                value-format="yyyyMMdd"
                format="yyyy/MM/dd"
                :picker-options="endPickerOptions"
                :clearable="false"
                :editable="false"
                style="width:132px"
                @change="handleDateChange"
            >
                <!-- @change="dateChange('end')" -->
            </el-date-picker>
            <!-- <el-date-picker
                v-model="dateRange"
                type="daterange"
                size="mini"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyyMMdd"
                format="yyyy/MM/dd"
                :picker-options="pickerOptions"
                style="width:205px; margin:0 6px;"
                @change="handleRange"
            >
            </el-date-picker> -->
            <div class="btn" @click="handleBtn">生成走势图</div>
            <!-- <el-button size="mini" type="primary" class="btn" @click="handleBtn">生成走势图</el-button> -->
        </div>
        <ItemSyncDetail
            :show="detailShow"
            v-if="detailShow"
            :info="{
                ...info,
                ...currentData,
                successNum: data['succeed'].value,
                errorNum: data['failed'].value,
            }"
            :syncExtraParams="{
                ...lineParams,
                syncStatus: [currentData.seriesIndex],
                dataTime: dataTime,
            }"
            :riskEntryTypeObj="riskEntryTypeObj"
            @item-sync-detail="itemSyncDetailHandle"
            @getDetailDataChange="getDetailDataChange"
        ></ItemSyncDetail>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import * as echarts from 'echarts';
import moment from 'moment';
import ItemSyncDetail from './item-sync-detail.vue';
@Component({
    name: 'ItemLine',
    components: {
        ItemSyncDetail,
    },
})
export default class ItemLine extends Vue {
    @Prop() data: any[];
    @Prop() info: any;
    @Prop() riskEntryTypeObj: any;
    @Prop() dateTimeData: any[];
    chartInstance: any = null;

    // date: any = moment(new Date()).format('yyyy/MM/DD');
    // dateRange: any[] = [moment(new Date()).format('yyyyMMDD'), moment(new Date()).format('yyyyMMDD')];

    detailShow: boolean = false;
    currentData: any = {};
    lineParams: any = {
        beginDate: moment(new Date()).format('yyyyMMDD'),
        endDate: moment(new Date()).format('yyyyMMDD'),
    };
    unit: string = 'hour'; // 时间轴单位
    dataTime: string = ''; // 横轴时间

    @Watch('data', { immediate: true, deep: true })
    onWatchData(newData) {
        if (newData) {
            let that = this;
            this.$nextTick(() => {
                that.updateChart();
            });
        }
    }

    beginPickerOptions: any = {
        disabledDate: time => {
            let minDate;
            let maxDate = new Date().getTime();
            let endDate = this.lineParams.endDate;
            if (endDate) {
                minDate = moment(endDate)
                    .subtract(1, 'year')
                    .valueOf();
            }
            return time.getTime() > maxDate || time.getTime() < minDate;
        },
    };

    endPickerOptions: any = {
        disabledDate: time => {
            let minDate;
            let date1 = new Date().getTime();
            let beginDate = this.lineParams.beginDate;
            let date2 = moment(beginDate)
                .add(1, 'year')
                .valueOf();
            if (beginDate) {
                minDate = moment(beginDate).valueOf();
            }
            let maxDate = date1 > date2 ? date2 : date1;
            return time.getTime() > maxDate || time.getTime() < minDate;
        },
    };

    handleClick(seriesName: string, data: string, name: string, seriesIndex: number) {
        this.handleXlabel(name);
        // console.log(this.dateTime);

        this.detailShow = true;
        this.currentData = {
            seriesName: seriesName == '同步成功' ? '成功' : '失败',
            data: data,
            time: name,
            seriesIndex: seriesIndex == 0 ? 1 : 0, // 注意:页面对应0是成功;但是实际1才是成功
        };
        console.log(this.dateTimeData, name, 'name-------');
    }

    // 处理日期变化
    handleDateChange() {
        let startDate = this.lineParams.beginDate;
        let endDate = this.lineParams.endDate;
        let days = moment(endDate, 'YYYYMMDD').diff(moment(startDate, 'YYYYMMDD'), 'days');
        let months = moment(endDate, 'YYYYMMDD').diff(moment(startDate, 'YYYYMMDD'), 'months');
        let years = moment(endDate, 'YYYYMMDD').diff(moment(startDate, 'YYYYMMDD'), 'years');

        if (days == 0) {
            this.unit = 'hour';
        } else if (days > 0 && months == 0) {
            this.unit = 'day';
        } else if (months > 0 && years == 0) {
            this.unit = 'month';
        }
    }

    mounted() {
        window.handleClick = this.handleClick;
        this.initChart();
        this.updateChart();
    }

    // 生成走势图
    handleBtn() {
        this.$emit('generate-trend', this.lineParams);
    }

    initChart() {
        let that = this;
        this.chartInstance = echarts.init(this.$refs.chartDom);
        let initOption = {
            title: {
                show: false,
                text: `{a|}{b|条目同步走势}`,
                textStyle: {
                    color: 'black',
                    fontWeight: 'bold',
                    rich: {
                        a: {
                            width: 12,
                            height: 12,
                            borderRadius: 50,
                            borderWidth: 4,
                            borderColor: '#2288ff',
                            borderType: 'solid',
                            verticalAlign: 'top', // 对齐方式
                        },
                        b: {
                            fontWeight: 'bold',
                            fontSize: 15,
                            padding: [0, 0, 0, 5],
                        },
                    },
                },
            },
            tooltip: {
                trigger: 'item',
                triggerOn: 'mousemove',
                enterable: true, // 鼠标是否可进入提示框浮层中
                confine: true, // 是否将 tooltip 框限制在图表的区域内
                extraCssText: 'z-index: 99;', // 额外附加到浮层的 css 样式
                showDelay: 200,
                hideDelay: 100,
                position: function(p) {
                    // 其中p为当前鼠标的位置
                    return [p[0] + 15, p[1] - 15];
                },
                // alwaysShowContent: true,
                formatter: param => {
                    const marker = param.marker;
                    const data = param.data;
                    const seriesName = param.seriesName;
                    const color = param.color;
                    const name = param.name;
                    const seriesIndex = param.seriesIndex;
                    return `${marker}${seriesName}:<span style="border-bottom:1px solid ${color};color:${color};margin:0 3px;font-size:8px;cursor:pointer;" onclick="handleClick('${seriesName}','${data}','${name}','${seriesIndex}')">${data}次</span>${name}`;
                },
                // backgroundColor: '#f5f5f5',
                // borderColor: '#ffffff',
                // textStyle: {
                //     color: '#6f6d6d',
                //     fontSize: 12,
                // },
            },
            legend: {
                icon: 'rect',
                selectedMode: false,
                left: '40%',
                top: '35px',
                itemHeight: 3,
                itemWidth: 15,
                textStyle: {
                    color: '#9aa8ba',
                    fontSize: 14,
                },
            },
            grid: {
                left: '3%',
                right: '3%',
                width: '94%', // 宽度
                bottom: '5%',
                // height: '56%', // 高度
                top: '75px',
                containLabel: true,
            },
            // toolbox: {
            //     show: true,
            //     itemSize: 17,
            //     showTitle: false,
            //     top: 2,
            //     right: 390,
            //     feature: {
            //         myTool1: {
            //             show: true,
            //             title: '刷新',
            //             icon:
            //                 'path://M894.481158 505.727133c0 49.589418-9.711176 97.705276-28.867468 143.007041-18.501376 43.74634-44.98454 83.031065-78.712713 116.759237-33.728172 33.728172-73.012897 60.211337-116.759237 78.712713-45.311998 19.156292-93.417623 28.877701-143.007041 28.877701s-97.695043-9.721409-142.996808-28.877701c-43.756573-18.501376-83.031065-44.98454-116.76947-78.712713-33.728172-33.728172-60.211337-73.012897-78.712713-116.759237-19.156292-45.301765-28.867468-93.417623-28.867468-143.007041 0-49.579185 9.711176-97.695043 28.867468-142.996808 18.501376-43.74634 44.98454-83.031065 78.712713-116.759237 33.738405-33.728172 73.012897-60.211337 116.76947-78.712713 45.301765-19.166525 93.40739-28.877701 142.996808-28.877701 52.925397 0 104.008842 11.010775 151.827941 32.745798 46.192042 20.977777 86.909395 50.79692 121.016191 88.608084 4.389984 4.860704 8.646937 9.854439 12.781094 14.97097l0-136.263453c0-11.307533 9.168824-20.466124 20.466124-20.466124 11.307533 0 20.466124 9.15859 20.466124 20.466124l0 183.64253c0 5.433756-2.148943 10.632151-5.986341 14.46955-3.847631 3.837398-9.046027 5.996574-14.479783 5.996574l-183.64253-0.020466c-11.307533 0-20.466124-9.168824-20.466124-20.466124 0-11.307533 9.168824-20.466124 20.466124-20.466124l132.293025 0.020466c-3.960195-4.952802-8.063653-9.782807-12.289907-14.479783-30.320563-33.605376-66.514903-60.098773-107.549481-78.753645-42.467207-19.289322-87.850837-29.072129-134.902456-29.072129-87.195921 0-169.172981 33.9533-230.816946 95.597265-61.654198 61.654198-95.597265 143.621025-95.597265 230.816946s33.943067 169.172981 95.597265 230.816946c61.643965 61.654198 143.621025 95.607498 230.816946 95.607498s169.172981-33.9533 230.816946-95.607498c61.654198-61.643965 95.597265-143.621025 95.597265-230.816946 0-11.2973 9.168824-20.466124 20.466124-20.466124C885.322567 485.261009 894.481158 494.429833 894.481158 505.727133z',
            //             //   设置颜色时放开
            //             iconStyle: {
            //                 borderColor: '#7b7b7b',
            //             },
            //             emphasis: {
            //                 iconStyle: {
            //                     borderColor: '#91cc75',
            //                 },
            //             },
            //             onclick: () => {
            //                 this.refresh();
            //             },
            //         },
            //     },
            // },
            xAxis: {
                type: 'category',
                nameTextStyle: {
                    color: '#aaaaaa',
                },
                axisTick: {
                    inside: true,
                },
                axisLine: {
                    lineStyle: {
                        color: 'gray',
                        width: 1,
                    },
                },
                axisLabel: {
                    fontSize: 8,
                    textStyle: {
                        color: '#b3b7c2',
                    },
                },
                boundaryGap: false,
                data: this.data['tags'],
                // data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            },
            yAxis: {
                type: 'value',
                scale: true,
                // min: 0,
                // max: 'dataMax',
                // splitNumber: 4,
                // min: () => {
                //     // 获取y轴的刻度区间大小
                //     console.log(this.chartInstance.getModel().getComponent('yAxis').axis.scale._interval);
                //     let interval = this.chartInstance.getModel().getComponent('yAxis').axis.scale._interval;
                //     return interval;
                // },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: 'gray',
                        width: 1,
                    },
                },

                axisLabel: {
                    show: true,
                    showMinLabel: false, // 不显示最小刻度
                    textStyle: {
                        // color: '#C5DFFB',
                        color: '#b3b7c2',
                    },
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#1e374e',
                        type: 'dashed',
                    },
                },
            },
            series: [
                {
                    stack: '同步失败',

                    name: '同步成功',
                    type: 'line',
                    // position: 'top',
                    symbol: 'circle',
                    // symbol: 'none', // 去除小圆点
                    smooth: true, // 曲线
                    // showSymbol: false,
                    emphasis: {
                        focus: 'series',
                    },
                    symbolSize: [4, 4],
                    // 折线区域颜色
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#0a493a' },
                                { offset: 1, color: '#081e36' },
                            ]),
                        },
                    },
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                color: '#04b837',
                            },
                        },
                    },
                    // stack: true,
                    data: this.data['succeed'],
                    // data: [33, 28, 22, 28, 35, 40, 35, 26, 30, 28, 28, 36],
                },
                {
                    stack: '同步失败',
                    name: '同步失败',
                    type: 'line',
                    // position: 'bottom',
                    symbol: 'circle',
                    // symbol: 'none', // 去除小圆点
                    emphasis: {
                        focus: 'series',
                    },
                    // showSymbol: false,
                    symbolSize: [4, 4],
                    // 折线区域颜色
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#4f2138' },
                                { offset: 1, color: '#151533' },
                            ]),
                        },
                    },
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                color: '#fa4343',
                            },
                        },
                    },
                    // stack: true,
                    data: this.data['failed'],
                    // data: [21, 25, 30, 36, 43, 46, 41, 30, 15, 7, 7, 30],
                },
            ],
            color: ['#70b603', '#d9001b'],
        };
        this.chartInstance.setOption(initOption);
        // 点击事件
        this.chartInstance.on('click', param => {
            this.handleClick(param.seriesName, param.data, param.name, param.seriesIndex);
        });
    }

    /**
     * 获取完整当前横轴点对应的时间
     */
    handleXlabel(name) {
        let dataTime = '';
        let xlabel = '';
        if (this.unit == 'hour') {
            xlabel = name.substr(0, 2);
            dataTime = this.lineParams.beginDate + xlabel;
        } else if (this.unit == 'day') {
            xlabel = name.replace(/\//g, '');
            dataTime = this.lineParams.beginDate.substr(0, 4) + xlabel;
            // dataTime = this.dateTimeData.find((ele: any) => ele.indexOf(xlabel) !== -1);
        } else if (this.unit == 'month') {
            xlabel = name.replace(/\//g, '');
            dataTime = xlabel;
        }
        this.dataTime = dataTime;
    }

    updateChart() {
        const dataOption = {
            xAxis: { data: this.data['tags'] },
            series: [{ data: this.data['succeed'] }, { data: this.data['failed'] }],
        };
        this.chartInstance.setOption(dataOption);
    }

    dispose() {
        this.chartInstance.dispose(); // 销毁实例
        this.initChart();
    }

    // handleRange(arr) {
    //     if (arr) {
    //         this.lineParams.beginDate = arr[0];
    //         this.lineParams.endDate = arr[1];
    //     } else {
    //         this.lineParams.beginDate = 0;
    //         this.lineParams.endDate = 0;
    //     }
    // }

    // @Watch('lineParams', { deep: true })
    dateChange(val) {
        console.log(val);
        let begin = this.lineParams.beginDate;
        let end = this.lineParams.endDate;
        let value = moment(this.lineParams.beginDate).to(moment(this.lineParams.endDate), true);
        console.log(value, '-------------');
    }

    refresh() {
        this.$emit('refresh', '条目同步走势');
    }

    // 同步明细数据数量变化回调
    getDetailDataChange(args: any) {
        // 被动刷新图表数据
        this.$emit('getDetailDataChange', args);
    }

    // 同步明细回调
    itemSyncDetailHandle() {
        this.detailShow = false;
    }

    beforeDestroy() {
        this.chartInstance.clear();
        this.chartInstance.dispose();
        this.chartInstance = null;
    }
}
</script>

<style lang="scss" scoped>
.com-chart {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.select-content {
    position: absolute;
    right: 1%;
    top: 1%;
    display: flex;
    .btn {
        cursor: pointer;
        margin-left: 4px;
        background-repeat: no-repeat;
        background-size: 100% 100%;
        width: 100px;
        text-align: center;
        line-height: 26px;
        color: white;
        background-image: url('../images/entry-monitor/btn-box.png');
    }
}

/deep/ .el-date-editor .el-range-separator {
    padding: 0 15px 0 0px;
}
/deep/ .el-picker-panel {
    background-color: #191e2d !important;
    border: none;
}
.select-content {
    /deep/ .el-input__inner {
        background-color: rgba(255, 255, 255, 0);
        color: white;
        border-color: #7183a5;
    }
}
</style>
<style lang="scss">
.el-picker-panel {
    background-color: #191e2d !important;
    // background-color: #595a5e !important;

    border: none;
}
.el-picker-panel__icon-btn {
    color: #fff;
}
.el-date-table td {
    color: white;
    .disabled div {
        background-color: #5c5c5e !important;
    }
}
.el-date-table td.disabled div {
    background-color: #575757;
    // opacity: 1;
    // cursor: not-allowed;
    // color: #C5C6C7;
}
// .el-date-table td.disabled div
.el-date-table td.next-month,
.el-date-table td.prev-month {
    color: #595a5e;
}

.chart-btn-refresh {
    cursor: pointer;
    width: 32px;
    height: 32px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url('../images/entry-monitor/refresh-icon.png');
}
</style>
